<script setup>
import { ref, watch, computed, onMounted, provide, nextTick, shallowRef } from 'vue'
import { RouterLink, RouterView, useRoute, useRouter } from 'vue-router'
import { adminAPI } from './api/api'
import { ElMessage } from 'element-plus'
import { useAdminStore } from './stores/admin' // 新增导入

const adminStore = useAdminStore()
const route = useRoute()
const router = useRouter()
const menus = shallowRef([])
const isCollapse = ref(false)
const activeMenu = ref('')
const isLoggedIn = computed(() => adminStore.isLoggedIn)  // 使用 store 的计算属性
const isMenuLoaded = ref(false)
const isChecking = ref(false)
const lastCheckTime = ref(0)

// 标签页管理
const visitedViews = shallowRef([])
const activeTab = ref('')

// 提供登录状态和退出登录方法给子组件使用
provide('isLoggedIn', isLoggedIn)
provide('logout', logout)

// 强制刷新页面
const forceReload = () => {
  window.location.reload(true)
}

// 面包屑导航
const breadcrumbs = computed(() => {
  const currentPath = route.path
  const result = []

  const findMenu = (menuList) => {
    for (const menu of menuList) {
      if ((currentPath === menu.component || currentPath.startsWith(menu.component + '/')) && menu.name) {
        result.push({
          name: menu.name,
          path: menu.component
        })

        if (menu.children && menu.children.length > 0) {
          findMenu(menu.children)
        }

        return true
      }

      if (menu.children && menu.children.length > 0) {
        if (findMenu(menu.children)) {
          return true
        }
      }
    }
    return false
  }

  findMenu(menus.value)
  return result
})

// 获取当前路由对应的菜单名称
const getMenuName = (path) => {
  let title = '未知页面'

  const findMenuTitle = (menuList) => {
    for (const menu of menuList) {
      if (path === menu.component) {
        return menu.name
      }

      if (menu.children && menu.children.length > 0) {
        const childTitle = findMenuTitle(menu.children)
        if (childTitle) return childTitle
      }
    }
    return null
  }

  const menuTitle = findMenuTitle(menus.value)

  // 如果是首页路径，返回"首页"
  if (path === '/' || path === '') {
    return '首页'
  }

  return menuTitle || title
}

// 添加标签页
const addVisitedView = (view) => {
  // 检查是否已存在相同路径的标签页，如果存在则不添加
  if (visitedViews.value.some(v => v.path === view.path)) {
    // 只更新已有标签页的标题，以防标题发生变化
    const index = visitedViews.value.findIndex(v => v.path === view.path)
    if (index !== -1) {
      const title = view.meta?.title || getMenuName(view.path)
      if (title && visitedViews.value[index].title !== title) {
        visitedViews.value[index].title = title
      }
    }
    return
  }

  visitedViews.value.push({
    path: view.path,
    name: view.name || getMenuName(view.path),
    title: view.meta?.title || getMenuName(view.path)
  })
}

// 删除标签页
const closeTab = (path) => {
  const index = visitedViews.value.findIndex(v => v.path === path)
  if (index === -1) return

  // 如果关闭的是当前激活的标签页，需要切换到其他标签页
  if (activeTab.value === path) {
    const nextTab = visitedViews.value[index + 1] || visitedViews.value[index - 1]
    if (nextTab) {
      router.push(nextTab.path)
    } else {
      router.push('/')
    }
  }

  visitedViews.value.splice(index, 1)
}

// 切换标签页
const switchTab = (path) => {
  activeTab.value = path
  router.push(path)
}

// 处理菜单折叠
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

// 处理菜单选择
const handleMenuSelect = (index) => {
  // 如果已经打开了这个标签页，只需要激活它
  const existTab = visitedViews.value.find(tab => tab.path === index)
  if (existTab) {
    activeTab.value = index
    router.push(index)
    return
  }

  // 获取菜单标题和路由元信息
  const title = getMenuName(index)
  const routeInfo = router.resolve(index)

  // 添加新标签页
  visitedViews.value.push({
    path: index,
    name: routeInfo.name || title,
    title: routeInfo.meta?.title || title
  })

  // 激活这个标签页并导航到对应路由
  activeTab.value = index
  router.push(index)
}

// 将路由路径转换为菜单路径
const convertRoutePathToMenuPath = (routePath) => {
  // 处理特殊情况：如果是根路径
  if (routePath === '/') return '/dashboard'

  // 遍历菜单，查找匹配的菜单路径
  const findMatchingMenuPath = (menuList) => {
    for (const menu of menuList) {
      // 如果路由路径精确匹配菜单路径
      if (routePath === menu.component || routePath.startsWith(menu.component + '/')) {
        return menu.component
      }

      // 递归检查子菜单
      if (menu.children && menu.children.length > 0) {
        const result = findMatchingMenuPath(menu.children)
        if (result) return result
      }
    }
    return null
  }

  const menuPath = findMatchingMenuPath(menus.value)
  return menuPath || routePath
}

// 初始化默认首页标签
const initDefaultTab = () => {
  // 添加首页标签
  if (visitedViews.value.length === 0) {
    visitedViews.value.push({
      path: '/',
      name: '首页',
      title: '首页'
    })
  }

  // 如果当前路由不是首页，添加当前路由对应的标签
  if (route.path !== '/' && route.path !== '' && route.path !== '/login') {
    addVisitedView({
      path: route.path,
      name: route.name,
      meta: route.meta
    })
  }

  // 设置当前激活的标签
  activeTab.value = route.path === '/login' ? '/' : route.path
}

// 检查登录状态
const checkLoginStatus = async () => {
  // 防止频繁重复检查
  const now = Date.now();
  if (isChecking.value || (now - lastCheckTime.value < 3000)) {
    return;
  }
  
  try {
    isChecking.value = true;
    lastCheckTime.value = now;
    
    const result = await adminAPI.getStatus();
    const loginStatus = result.code === 200;
    
    if (loginStatus) {
      // 已登录，获取菜单数据，并使用重试机制
      let menuResult = await getMenuData();
      
      // 如果首次加载失败，延迟500ms后重试一次
      if (!menuResult) {
        console.log('首次加载菜单失败，500ms后重试...');
        await new Promise(resolve => setTimeout(resolve, 500));
        menuResult = await getMenuData();
      }
      
      // 如果菜单加载失败，清除登录状态并跳转到登录页
      if (!menuResult) {
        console.error('多次尝试加载菜单失败，重置登录状态');
        isMenuLoaded.value = false;
        adminStore.logout();
        
        if (route.path !== '/login') {
          router.push('/login');
        }
        return;
      }
      
      // 如果当前路径是登录页，则重定向到首页
      if (route.path === '/login') {
        router.push('/');
      }
    } else {
      // 未登录，跳转到登录页
      adminStore.logout();
      if (route.path !== '/login') {
        router.push('/login');
      }
    }
  } catch (error) {
    // console.error('检查登录状态失败', error);
    isMenuLoaded.value = false;
    adminStore.logout();
    
    // 发生错误时，重定向到登录页
    if (route.path !== '/login') {
      router.push('/login');
    }
  } finally {
    isChecking.value = false;
  }
}

// 退出登录
async function logout() {
  try {
    // 先清除状态，防止界面不一致
    isMenuLoaded.value = false;
    menus.value = [];
    visitedViews.value = [];
    
    // 清除 store 中的状态
    adminStore.logout();
    
    // 再请求后端退出接口
    await adminAPI.logout();
    ElMessage.success('退出登录成功');
    
    // 等待DOM更新后再跳转，避免白屏
    await nextTick();
    router.push('/login');
  } catch (error) {
    console.error('退出登录失败', error);
    router.push('/login');
    ElMessage.error('退出登录失败，但已清除本地登录状态');
  }
}

// 获取菜单数据
const getMenuData = async () => {
  try {
    // 如果菜单已加载，不重复请求
    if (isMenuLoaded.value && menus.value.length > 0) {
      return true;
    }
    
    console.log('正在获取菜单数据...');
    const result = await adminAPI.getMenus();
    console.log('菜单数据响应:', result);
    
    // 1. 先检查响应状态
    if (result.code !== 200) {
      console.error('获取菜单响应码错误', result.code);
      return false;
    }
    
    // 2. 再检查数据是否存在
    if (!result.data) {
      console.error('菜单数据为null或undefined');
      return false;
    }
    
    // 3. 检查是否为数组
    if (!Array.isArray(result.data)) {
      console.error('菜单数据不是数组格式', result.data);
      // 尝试兼容处理
      if (typeof result.data === 'object') {
        // 如果是对象，尝试找到可能的菜单数组
        for (const key in result.data) {
          if (Array.isArray(result.data[key]) && result.data[key].length > 0) {
            console.log('从对象中找到菜单数组:', key);
            menus.value = result.data[key];
            isMenuLoaded.value = true;
            await nextTick();
            initDefaultTab();
            return true;
          }
        }
      }
      return false;
    }
    
    // 4. 检查数组是否非空
    if (result.data.length === 0) {
      console.warn('获取到空菜单数组');
      // 创建一个默认的菜单项，确保至少有首页
      menus.value = [
        {
          id: 1,
          name: '首页',
          component: '/',
          icon: 'HomeFilled'
        }
      ];
      isMenuLoaded.value = true;
      await nextTick();
      initDefaultTab();
      return true;
    }
    
    // 正常处理
    menus.value = result.data;
    isMenuLoaded.value = true;
    await nextTick();
    initDefaultTab();
    console.log('菜单加载成功，项目数:', menus.value.length);
    return true;
  } catch (apiError) {
    console.error('从API获取菜单失败:', apiError);
    // 创建一个默认的菜单项，确保至少有首页，避免白屏
    if (menus.value.length === 0) {
      menus.value = [
        {
          id: 1,
          name: '首页',
          component: '/',
          icon: 'HomeFilled'
        }
      ];
      isMenuLoaded.value = true;
      await nextTick();
      initDefaultTab();
      return true;
    }
    return false;
  }
}

// 在组件挂载时初始化
onMounted(async () => {
  try {
    // 检查登录状态
    if (adminStore.isLoggedIn) {
      console.log('从 store 恢复登录状态');
      
      // 如果已登录但当前在登录页，跳转到首页
      if (route.path === '/login') {
        router.push('/');
      }
      
      // 后台加载菜单数据，不阻塞UI
      getMenuData()
        .then(success => {
          if (success) {
            console.log('菜单加载成功');
            // 使用当前路由路径更新激活的菜单和标签页
            if (route.path !== '/login') {
              updateActiveMenuAndTab(route.path);
            }
          } else {
            console.warn('菜单加载失败，尝试重新加载');
            // 如果菜单加载失败，不影响当前UI，但在后台重试一次
            setTimeout(() => {
              getMenuData().catch(console.error);
            }, 1000);
          }
        })
        .catch(console.error);
    } else {
      // 如果没有登录状态，检查登录状态
      await checkLoginStatus();
    }
  
    // 监听路由变化，更新选中的菜单和标签页
    watch(() => route.path, (newPath, oldPath) => {
      // 避免相同路径的重复跳转
      if (newPath === oldPath) return;
      
      // 如果是登录页或未登录，不处理
      if (newPath === '/login' || !isLoggedIn.value) return;
      
      // 如果菜单未加载，尝试重新加载菜单
      if (!isMenuLoaded.value || menus.value.length === 0) {
        getMenuData().then(success => {
          if (success) {
            updateActiveMenuAndTab(newPath);
          }
        });
        return;
      }
      
      updateActiveMenuAndTab(newPath);
    }, { immediate: true }); // 添加immediate以确保初始路由正确处理
  } catch (error) {
    console.error('组件挂载初始化失败:', error);
    // 发生错误时重置状态
    isLoggedIn.value = false;
    isMenuLoaded.value = false;
    
    if (route.path !== '/login') {
      router.push('/login');
    }
  }
});

// 更新活动菜单和标签页的函数
const updateActiveMenuAndTab = (newPath) => {
  try {
    // 更新活动菜单 - 需要从路由路径转换回菜单路径
    const menuPath = convertRoutePathToMenuPath(newPath);
    activeMenu.value = menuPath;
  
    // 如果标签页列表中已存在当前路径，只需激活它
    const existTab = visitedViews.value.find(tab => tab.path === newPath);
    if (existTab) {
      activeTab.value = newPath;
      return;
    }
  
    // 获取路由信息
    const routeInfo = router.resolve(newPath);
    const title = routeInfo.meta?.title || getMenuName(menuPath);
  
    // 使用nextTick减少闪烁
    nextTick(() => {
      // 添加新标签页
      addVisitedView({
        path: newPath,
        name: routeInfo.name,
        meta: routeInfo.meta
      });
  
      // 激活新标签页
      activeTab.value = newPath;
    });
  } catch (error) {
    console.error('更新菜单和标签页失败:', error);
  }
};
</script>

<template>
  <!-- 登录页面 -->
  <RouterView v-if="route.path === '/login'" />
  
  <!-- 管理界面 -->
  <div v-else-if="isLoggedIn && isMenuLoaded" class="admin-layout">
    <!-- 侧边栏 -->
    <div class="sidebar" :class="{ 'is-collapse': isCollapse }">
      <div class="logo-container">
        <img alt="系统Logo" class="logo" src="@/assets/logo.svg" width="30" height="30" />
        <span v-if="!isCollapse" class="title">ADMIN</span>
      </div>

      <div class="menu-container">
        <el-menu :default-active="activeMenu" class="el-menu-vertical" :collapse="isCollapse" background-color="#304156"
          text-color="#bfcbd9" active-text-color="#409EFF" router @select="handleMenuSelect">

          <template v-for="menu in menus" :key="menu.id">
            <!-- 有子菜单的情况 -->
            <el-sub-menu v-if="menu.children && menu.children.length > 0" :index="menu.component">
              <template #title>
                <el-icon v-if="menu.icon">
                  <component :is="menu.icon" />
                </el-icon>
                <span>{{ menu.name }}</span>
              </template>

              <!-- 二级菜单 -->
              <template v-for="subMenu in menu.children" :key="subMenu.id">
                <!-- 有三级菜单的情况 -->
                <el-sub-menu v-if="subMenu.children && subMenu.children.length > 0" :index="subMenu.component">
                  <template #title>
                    <span>{{ subMenu.name }}</span>
                  </template>

                  <!-- 三级菜单项 -->
                  <el-menu-item v-for="childMenu in subMenu.children" :key="childMenu.id" :index="childMenu.component">
                    <span>{{ childMenu.name }}</span>
                  </el-menu-item>
                </el-sub-menu>

                <!-- 没有子菜单的情况 -->
                <el-menu-item v-else :index="subMenu.component">
                  <span>{{ subMenu.name }}</span>
                </el-menu-item>
              </template>
            </el-sub-menu>

            <!-- 没有子菜单的情况 -->
            <el-menu-item v-else :index="menu.component">
              <el-icon v-if="menu.icon">
                <component :is="menu.icon" />
              </el-icon>
              <span>{{ menu.name }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-container">
      <!-- 头部导航栏 -->
      <div class="navbar">
        <div class="left-area">
          <el-icon class="toggle-button" @click="toggleSidebar">
            <component :is="isCollapse ? 'Expand' : 'Fold'" />
          </el-icon>

          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index" :to="{ path: item.path }">
              {{ item.name }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="right-area">
          <el-dropdown>
            <span class="user-info">
              {{ adminStore.getUserInfo?.realName || '管理员' }} <el-icon><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>个人信息</el-dropdown-item>
                <el-dropdown-item>修改密码</el-dropdown-item>
                <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 标签页导航 -->
      <div class="tabs-view-container">
        <el-scrollbar>
          <div class="tabs-wrapper">
            <el-tabs v-model="activeTab" type="card" @tab-click="tab => switchTab(tab.props.name)" closable
              @tab-remove="closeTab">
              <el-tab-pane v-for="item in visitedViews" :key="item.path" :label="item.title" :name="item.path">
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-scrollbar>
      </div>

      <!-- 内容主体 -->
      <div class="app-main">
        <RouterView v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <keep-alive>
              <component :is="Component" />
            </keep-alive>
          </transition>
        </RouterView>
      </div>
    </div>
  </div>
  
  <!-- 加载中状态：已登录但菜单未加载完成 -->
  <div v-else-if="isLoggedIn && !isMenuLoaded" class="loading-container">
    <el-card shadow="never" style="width: 100%; max-width: 600px;">
      <div style="text-align: center; padding: 20px;">
        <img alt="系统Logo" src="@/assets/logo.svg" width="60" height="60" style="margin-bottom: 20px" />
        <h2>正在加载系统资源...</h2>
        <el-progress :percentage="50" :indeterminate="true" style="margin: 20px 0;" />
        <p class="loading-tip">如果长时间未加载完成，请尝试<a href="javascript:void(0)" @click="forceReload">刷新页面</a></p>
      </div>
    </el-card>
  </div>
  
  <!-- 未登录或未知状态 -->
  <div v-else class="loading-container">
    <el-card shadow="hover" style="width: 100%; max-width: 500px;">
      <div style="text-align: center; padding: 20px;">
        <h2>正在检查登录状态...</h2>
        <el-progress :percentage="30" :indeterminate="true" style="margin: 20px 0;" />
        <p class="loading-tip">正在为您跳转到合适的页面，请稍候...</p>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.admin-layout {
  display: flex;
  height: 100vh;
  width: 100%;
  /* 添加硬件加速，减少闪烁 */
  transform: translateZ(0);
  backface-visibility: hidden;
  perspective: 1000;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  padding: 20px;
}

.sidebar {
  width: 210px;
  height: 100%;
  background-color: #304156;
  transition: width 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  overflow-y: auto;
  overflow-x: hidden;
  flex-shrink: 0;
  position: relative;
  z-index: 10;
  /* 添加硬件加速，减少闪烁 */
  transform: translateZ(0);
  will-change: width;
}

.sidebar.is-collapse {
  width: 64px;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10px;
  background-color: #2b3649;
}

.logo {
  width: 30px;
  height: 30px;
}

.title {
  margin-left: 10px;
  color: #fff;
  font-weight: bold;
  font-size: 16px;
  white-space: nowrap;
}

.menu-container {
  margin-top: 10px;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 210px;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-width: 0;
  /* 防止flex子项目溢出 */
  /* 添加硬件加速，减少闪烁 */
  transform: translateZ(0);
}

.navbar {
  height: 50px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  position: relative;
  z-index: 9;
}

.left-area {
  display: flex;
  align-items: center;
  overflow: hidden;
}

.navbar .left-area .el-breadcrumb {
  padding-left: 10px;
  max-width: calc(100vw - 180px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.toggle-button {
  cursor: pointer;
  font-size: 20px;
  flex-shrink: 0;
}

.right-area {
  display: flex;
  align-items: center;
}

.user-info {
  cursor: pointer;
  display: flex;
  align-items: center;
}

/* 标签页样式 */
.tabs-view-container {
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  position: relative;
  z-index: 8;
}

.tabs-wrapper {
  padding: 0 10px;
}

.app-main {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f0f2f5;
  /* 添加硬件加速，减少闪烁 */
  transform: translateZ(0);
}

/* 响应式布局适配 */
@media (max-width: 992px) {
  .sidebar {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    transform: translateX(-100%);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    /* 添加平滑过渡 */
    transition: transform 0.3s cubic-bezier(0.645, 0.045, 0.355, 1), width 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  }

  .sidebar.is-collapse {
    transform: translateX(0);
    width: 210px;
  }

  .main-container {
    margin-left: 0;
  }

  .toggle-button {
    transform: rotate(180deg);
  }


}

@media (max-width: 768px) {
  .navbar {
    padding: 0 10px;
  }

  .right-area {
    margin-left: 10px;
  }

  .app-main {
    padding: 10px;
  }
}

@media (max-width: 576px) {
  .navbar .left-area .el-breadcrumb {
    max-width: calc(100vw - 120px);
  }
}

/* 添加全局修复Firefox闪烁问题的样式 */
:deep(.el-tabs__item) {
  transform: translateZ(0);
}

:deep(.el-tabs__nav) {
  transform: translateZ(0);
  will-change: transform;
}

/* 添加过渡动画样式 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

.loading-tip {
  color: #606266;
  margin-top: 15px;
  font-size: 14px;
}

.loading-tip a {
  color: #409EFF;
  text-decoration: none;
  padding: 0 4px;
}

.loading-tip a:hover {
  text-decoration: underline;
}
</style>
